package hk.m4s.lr.repair.test.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import framework.common.Constant;
import framework.common.zanetwork.core.ResponseCallback;
import framework.utils.SharedPreferencesUtils;
import hk.m4s.lr.repair.test.R;
import hk.m4s.lr.repair.test.model.FlashSaleModel;
import hk.m4s.lr.repair.test.model.HomeIconInfo;
import hk.m4s.lr.repair.test.model.ShopModel;
import hk.m4s.lr.repair.test.service.AccountSerive;
import hk.m4s.lr.repair.test.ui.adapter.CarShopLikeAdapter;
import hk.m4s.lr.repair.test.ui.adapter.CardRvAdapter;
import hk.m4s.lr.repair.test.ui.adapter.GoodsAdapter;
import hk.m4s.lr.repair.test.ui.adapter.GridViewAdapter;
import hk.m4s.lr.repair.test.ui.adapter.HomeGridViewAdapter;
import hk.m4s.lr.repair.test.ui.goods.FlashSaleActivity;
import hk.m4s.lr.repair.test.ui.goods.GoodsCarActivity;
import hk.m4s.lr.repair.test.ui.goods.GoodsEventActivity;
import hk.m4s.lr.repair.test.ui.goods.SearchActivity;
import hk.m4s.lr.repair.test.views.CustomSnapHelper;
import hk.m4s.lr.repair.test.views.InnerGridView;
import okhttp3.Response;

/**
 * Created by qi.wang on 2017/3/13.
 * 汽保商城
 */

public class CarShopFragment extends Fragment implements View.OnClickListener,GoodsAdapter.Listeners {
    private Context context;
    private LayoutInflater inflater;
    private Banner banner;
    private ViewPager viewpager;
    private ImageView leftBtn, rightBtn,shopping_car;
    private InnerGridView  car_shop_like, car_guess_like;
    private LinearLayout click_select;
    private TextView carNum,lookMore;
    private RelativeLayout flashSale;
    private GoodsAdapter goodsAdapter;
    private CarShopLikeAdapter carShopLikeAdapter;
    private RecyclerView rv;
    private List<HomeIconInfo> mPagerOneData = new ArrayList<>();
    public static List<ShopModel.ListRecommendBean> likeList = new ArrayList<>();
    public static List<ShopModel.ListGoodsBean> guessList = new ArrayList<>();
    public static List<ShopModel.ListGoodsBean> carList = new ArrayList<>();
    /**
     * 总的页数
     */
    private int pageCount;
    /**
     * 每一页显示的个数
     */
    private int pageSize = 4;
    /**
     * 当前显示的是第几页
     */
    private int curIndex = 0;
    private List<View> mPagerList;
    private List<ShopModel.ListAdGoodsBean> adList = new ArrayList<>();

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.car_shop_fragment_layout, container, false);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        // TODO Auto-generated method stub
        context = getActivity();
        inflater = LayoutInflater.from(context);
        findBaseView();
    }

    private void findBaseView() {
        banner = (Banner) this.getActivity().findViewById(R.id.banner);
        viewpager = (ViewPager) this.getActivity().findViewById(R.id.viewpager);
        car_shop_like = (InnerGridView) this.getActivity().findViewById(R.id.car_shop_like);
        car_guess_like = (InnerGridView) this.getActivity().findViewById(R.id.car_guess_like);
        rv = (RecyclerView)this.getActivity().findViewById(R.id.rv);
        carNum= (TextView) this.getActivity().findViewById(R.id.carNum);
        shopping_car= (ImageView) this.getActivity().findViewById(R.id.shopping_car);
        lookMore= (TextView) this.getActivity().findViewById(R.id.lookMore);
        click_select=(LinearLayout) this.getActivity().findViewById(R.id.click_select);
        flashSale=(RelativeLayout)this.getActivity().findViewById(R.id.flashSale);
        rv.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        CustomSnapHelper mMySnapHelper = new CustomSnapHelper();
        mMySnapHelper.attachToRecyclerView(rv);
        carShopLikeAdapter = new CarShopLikeAdapter(context, likeList);
        car_shop_like.setAdapter(carShopLikeAdapter);
        goodsAdapter = new GoodsAdapter(context, guessList);
        car_guess_like.setAdapter(goodsAdapter);
        car_shop_like.setOnItemClickListener(clickItems);
        click_select.setOnClickListener(this);
        flashSale.setOnClickListener(this);
        lookMore.setOnClickListener(this);
        shopping_car.setOnClickListener(this);
        initData();
        getIndex();
    }

    @Override
    public void onClick(View v) {
       switch (v.getId()){
           case R.id.click_select:
                Intent in=new Intent(getActivity(), SearchActivity.class);
               startActivity(in);
           break;
           case R.id.flashSale:
               Intent flashin=new Intent(getActivity(), FlashSaleActivity.class);
               startActivity(flashin);
               break;
           case R.id.lookMore:
               Intent lookin=new Intent(getActivity(), FlashSaleActivity.class);
               startActivity(lookin);
               break;
           case R.id.shopping_car:
               Intent lookCarin=new Intent(getActivity(), GoodsCarActivity.class);
               startActivity(lookCarin);
               break;
       }
    }

    public void getIndex() {
        Map<String, Object> parmas = new HashMap<>();
        parmas.put("device_type", Constant.device_type);
        parmas.put("userId", SharedPreferencesUtils.getSharedPreferences(Constant.userId, ""));
        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
        AccountSerive.index(context, parmas, new ResponseCallback<ShopModel>() {
            @Override
            public void onSuccess(ShopModel userinfoModel) {
                if (userinfoModel.getListAdGoods() != null) {
                    adList.clear();
                    adList.addAll(userinfoModel.getListAdGoods());
                    //设置指示器位置（当banner模式中有指示器时）
                    banner.setIndicatorGravity(BannerConfig.RIGHT);
                    //设置图片加载器
                    banner.setImageLoader(new GlideImageLoader());
                    //设置图片集合
                    banner.setImages(adList);
                    //banner设置方法全部调用完毕时最后调用
                    banner.start();
                    rv.setAdapter(new CardRvAdapter(getActivity(), adList));
                }

            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });

    }

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            ShopModel.ListAdGoodsBean bean = (ShopModel.ListAdGoodsBean) path;
            if (bean != null) {
                Glide.with(context).load(bean.getImage()).placeholder(R.mipmap.sebei_logo).error(R.mipmap.sebei_logo).into(imageView);
            }
        }

    }


    private void initData() {
        mPagerList = new ArrayList<View>();
        String[] iconName = getResources().getStringArray(R.array.home_bar_labels);
        //获取图片资源数组,方法是obtainTypeArray
        TypedArray typedArray = getResources().obtainTypedArray(R.array.home_bar_icon);
        for (int i = 0; i < iconName.length; i++) {
            //把数据装在第一个集合里,给第一个GridKView用
            HomeIconInfo homeIconInfo = new HomeIconInfo(iconName[i], typedArray.getResourceId(i, 0));
            //将iconName获取到的文本资源添加到第一个GridView数组里
            mPagerOneData.add(homeIconInfo);

        }
        pageCount = (int) Math.ceil(mPagerOneData.size() * 1.0 / pageSize);
        for (int i = 0; i < pageCount; i++) {
            // 每个页面都是inflate出一个新实例
            GridView gridView = (GridView) inflater.inflate(R.layout.home_gridview, viewpager, false);
            gridView.setAdapter(new HomeGridViewAdapter(context, mPagerOneData, i, pageSize));
            mPagerList.add(gridView);

            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    int pos = position + curIndex * pageSize;
                }
            });
        }
        //设置适配器
        viewpager.setAdapter(new ViewPagerAdapter(mPagerList));

        //超实惠
        likeList.clear();
        guessList.clear();
        ShopModel.ListRecommendBean bean1=new ShopModel.ListRecommendBean();
        bean1.setImages("");
        bean1.setGoods_name("超能双铂金火花塞1支装");
        bean1.setGoods_id("1");
        bean1.setPrice("20");
        ShopModel.ListRecommendBean bean2=new ShopModel.ListRecommendBean();
        bean2.setImages("");
        bean2.setGoods_name("车载尘器吸力超强120w干湿两用");
        bean2.setGoods_id("2");
        bean2.setPrice("20");
        ShopModel.ListRecommendBean bean3=new ShopModel.ListRecommendBean();
        bean3.setImages("");
        bean3.setGoods_name("美国杜邦空调清洗剂");
        bean3.setGoods_id("3");
        bean3.setPrice("20");
        likeList.add(bean1);
        likeList.add(bean2);
        likeList.add(bean3);
        carShopLikeAdapter.notifyDataSetChanged();
        ShopModel.ListGoodsBean bean4=new ShopModel.ListGoodsBean();
        bean4.setImages("");
        bean4.setGoods_name("超能双铂金火花塞1支装");
        bean4.setGoods_id("4");
        bean4.setPrice("20");
        ShopModel.ListGoodsBean bean5=new ShopModel.ListGoodsBean();
        bean5.setImages("");
        bean5.setGoods_name("车载尘器吸力超强120w干湿两用");
        bean5.setGoods_id("5");
        bean5.setPrice("20");
        ShopModel.ListGoodsBean bean6=new ShopModel.ListGoodsBean();
        bean6.setImages("");
        bean6.setGoods_name("美国杜邦空调清洗剂");
        bean6.setGoods_id("6");
        bean6.setPrice("20");
        ShopModel.ListGoodsBean bean7=new ShopModel.ListGoodsBean();
        bean7.setImages("");
        bean7.setGoods_name("美国杜邦空调清洗剂");
        bean7.setGoods_id("7");
        bean7.setPrice("20");
        guessList.add(bean4);
        guessList.add(bean5);
        guessList.add(bean6);
        guessList.add(bean7);
        goodsAdapter.setLoadingListener(this);
        goodsAdapter.notifyDataSetChanged();

    }

    class ViewPagerAdapter extends PagerAdapter {
        private List<View> mViewList;

        public ViewPagerAdapter(List<View> mViewList) {
            this.mViewList = mViewList;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViewList.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mViewList.get(position));
            return (mViewList.get(position));
        }

        @Override
        public int getCount() {
            if (mViewList == null)
                return 0;
            return mViewList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    @Override
    public void addCar(ShopModel.ListGoodsBean newsModel) {
        carList.add(newsModel);
        carNum.setVisibility(View.VISIBLE);
        carNum.setText(carList.size()+"");
    }
    AdapterView.OnItemClickListener clickItems = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // TODO Auto-generated method stub
            ShopModel.ListRecommendBean model = likeList.get(arg2);

            Intent aboutIntent = new Intent(getActivity(), GoodsEventActivity.class);
            aboutIntent.putExtra("goods_id",model.getGoods_id());
            startActivity(aboutIntent);
        }

    };
}
